#include <func.h>

#define MAXARGS 128

bool is_delim(const char* delim, char c) 
{
    const char* p = delim;
    while (*p) {
        if (*p == c) {
            return true;
        }
        p++;
    } // *p = '\0'
    return false;
}

char* my_strtok(char* str, const char* delim) 
{
    static char* start = NULL; // 初始化只执行一次
    if (str) {
        start = str;
    }
    // 移动 start, 找第一个不是分隔符的字符
    while (*start) {
        if (!is_delim(delim, *start)) {
            break;
        }
        start++;
    }  
    if (*start == '\0') return NULL;

    // 移动 curr, 找第一个是分隔符的字符
    char* curr = start;
    while (*curr) {
        if (is_delim(delim, *curr)) {
            break;
        }
        curr++;
    }
    char* result = start;
    if (*curr) {
        start = curr + 1;
        *curr = '\0';
    } else {
        start = curr;
    }
    return result;
}

int main(int argc, char* argv[])
{
    char message[] = "  ls  -l  \n";
    char* args[MAXARGS];
    
    int i = 0;
    args[i++] = my_strtok(message, " \t\n");
    while ((args[i++] = my_strtok(NULL, " \t\n")) != NULL)
        ;

    int j = 0;
    while (args[j]) {
        puts(args[j]);
        j++;
    }
    return 0;
}

